package com.coder520.login.controller;

import com.coder520.commom.utils.SecurityUtils;
import com.coder520.user.entity.User;
import com.coder520.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author 高鑫【gx_wanmei@163.com】
 * Created by 2017-6-21.16:42
 */
@Controller
@RequestMapping("login")
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     *@Author JackGao [gx_wanmei@163.com]
     *@Date 2017-6-21 19:05
     *@Description  登录页面
     */
    @RequestMapping
    public  String login()
    {
        return "login";
    }


    /**
     *@Author JackGao [gx_wanmei@163.com]
     *@Date 2017-6-21 19:05
     *@Description  校验登录
     */
    @RequestMapping("/check")
    @ResponseBody
    public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
       String username = request.getParameter("username");
       String pwd = request.getParameter("password");
       //查数据库 调用MD5对比密码
        User user=userService.findUserByUserName(username);
        if(user!=null)
        {
            if (SecurityUtils.checkPassword(pwd,user.getPassword()))
            {
                //校验成功
                //用户信息存session 返回成功signal
                request.getSession().setAttribute("userInfo",user);
                return "login_succ";
            }
            else
            {
                //校验失败 返回失败了signal
                return "login_fail";
            }
        }else
        {
            //校验失败 返回失败了signal
            return "login_fail";
        }


    }
    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user ) throws UnsupportedEncodingException, NoSuchAlgorithmException {
            userService.createUser(user);
            return "succ";

    }
}
